import 'package:equatable/equatable.dart';

/// AI聊天消息类型
enum AiMessageType {
  user('user'),
  ai('ai');

  const AiMessageType(this.value);
  final String value;
}

/// AI聊天消息模型
class AiChatMessageModel extends Equatable {
  /// 消息ID
  final String id;

  /// 消息类型（用户或AI）
  final AiMessageType messageType;

  /// 消息内容
  final String content;

  /// 发送时间
  final DateTime timestamp;

  /// 是否正在发送中
  final bool isSending;

  /// 是否发送失败
  final bool isFailed;

  /// 会话ID
  final String? conversationId;

  /// 显示时间（AI回复的显示时间）
  final int? showSec;

  const AiChatMessageModel({
    required this.id,
    required this.messageType,
    required this.content,
    required this.timestamp,
    this.isSending = false,
    this.isFailed = false,
    this.conversationId,
    this.showSec,
  });

  /// 从JSON创建消息对象
  factory AiChatMessageModel.fromJson(Map<String, dynamic> json) {
    return AiChatMessageModel(
      id: json['id'] as String,
      messageType: AiMessageType.values.firstWhere(
        (e) => e.value == json['messageType'],
        orElse: () => AiMessageType.user,
      ),
      content: json['content'] as String,
      timestamp: DateTime.parse(json['timestamp'] as String),
      isSending: json['isSending'] as bool? ?? false,
      isFailed: json['isFailed'] as bool? ?? false,
      conversationId: json['conversationId'] as String?,
      showSec: json['showSec'] as int?,
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'messageType': messageType.value,
      'content': content,
      'timestamp': timestamp.toIso8601String(),
      'isSending': isSending,
      'isFailed': isFailed,
      'conversationId': conversationId,
      'showSec': showSec,
    };
  }

  /// 复制并修改部分属性
  AiChatMessageModel copyWith({
    String? id,
    AiMessageType? messageType,
    String? content,
    DateTime? timestamp,
    bool? isSending,
    bool? isFailed,
    String? conversationId,
    int? showSec,
  }) {
    return AiChatMessageModel(
      id: id ?? this.id,
      messageType: messageType ?? this.messageType,
      content: content ?? this.content,
      timestamp: timestamp ?? this.timestamp,
      isSending: isSending ?? this.isSending,
      isFailed: isFailed ?? this.isFailed,
      conversationId: conversationId ?? this.conversationId,
      showSec: showSec ?? this.showSec,
    );
  }

  /// 验证消息内容是否有效
  bool get isValid => content.trim().isNotEmpty;

  @override
  List<Object?> get props => [
    id,
    messageType,
    content,
    timestamp,
    isSending,
    isFailed,
    conversationId,
    showSec,
  ];

  @override
  String toString() {
    return 'AiChatMessageModel(id: $id, messageType: $messageType, content: $content, timestamp: $timestamp)';
  }
}
